有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析时差

我在解析时差(我从网页上收到的)时感到困惑

例如:我得到如下字符串:2 years 10 weeks 3 days 6 hours 7 min ago。请注意yearweekdayhour中的尾随s在统一的情况下可能不在那里,并且在min中不存在

目前,我想得到这样存储的差异,并得到实际的日期和时间[通过从当前时间中减去?]

我不知道该怎么办?我知道时间解析方法,但这不是一个固定的时间,另外还有尾随的s

有人能提出一个好的方法吗


共 (3) 个答案

  1. # 1 楼答案

    我建议计算时间差是多少毫秒,然后从现在开始减去,这很简单,但是你会遇到闰年的问题

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, -2);
    cal.add(Calendar.WEEK_OF_YEAR, -10);
    cal.add(Calendar.DAY_OF_YEAR, -3);
    cal.add(Calendar.HOUR_OF_DAY, -6);
    cal.add(Calendar.MINUTE, -7);
    

    这应该很好,但我还没有测试过。例如,您还必须处理数周内无法获得值的情况

  2. # 2 楼答案

    根据@Eluvatar的建议,假设每个零件之间有一个空间:

    Calendar cal = Calendar.getInstance();
    String original = "2 years 10 weeks 3 days 6 hours 7 min ago";
    
    // Split on whitespace separators ("\s+" means "one or more whitespace characters"),
    // having trimmed whitespace at beginning and end.
    String[] split = original.trim().split("\s+");
    
    // Now parse each entry
    int num = split.length;
    int pos = 0;
    while ((num-pos) >= 2) {
        if (split[pos].regionMatches(true, 0, "year", 0, 4)) {
              cal.add(Calendar.YEAR, -Integer.decode(split[++pos]));
        }
        else if (split[pos].regionMatches(true, 0, "month", 0, 5)) {
              cal.add(Calendar.MONTH, -Integer.decode(split[++pos]));
        }
        else if (split[pos].regionMatches(true, 0, "week", 0, 4)) {
              cal.add(Calendar.WEEK_OF_YEAR, -Integer.decode(split[++pos]));
        }
        // And so on through the other potential values, note that the last
        // number in regionMatches is the number of characters to match.
    
        pos++;
    }
    

    “\s+”可能需要变成“\s+”,请参见How do I split a string with any whitespace chars as delimiters?

  3. # 3 楼答案

    您可以使用此代码。这考虑到了s和可能缺少一些令牌

    String orig = "2 years 10 weeks 3 days 6 hours 7 min ago";
    String[] split = orig.replaceAll("[^0-9]+", " ").trim().split(" ");
    Calendar cal = Calendar.getInstance();
    int idx = 0;
    if (orig.contains("yea")) cal.add(Calendar.YEAR, -Integer.parseInt(split[idx++]));
    if (orig.contains("wee")) cal.add(Calendar.WEEK_OF_MONTH, -Integer.parseInt(split[idx++]));
    if (orig.contains("day")) cal.add(Calendar.DATE, -Integer.parseInt(split[idx++]));
    if (orig.contains("hour")) cal.add(Calendar.HOUR, -Integer.parseInt(split[idx++]));
    if (orig.contains("min")) cal.add(Calendar.MINUTE, -Integer.parseInt(split[idx++]));
    
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
    String formattedString = sdf.format(cal.getTime());
    System.out.println(formattedString); // it prints 04-26-2011 02:12:54